//
//  ViewController.m
//  PFAMapDemo
//
//  Created by 原鹏飞 on 2018/11/5.
//  Copyright © 2018 原鹏飞. All rights reserved.
//

#import "MainVC.h"

#import <CoreLocation/CLLocationManager.h>      // 系统：定位管理类
#import "GPAuthorizationManager.h"              // 自定义：授权查询、管理工具类
#import "PFCitySelectorVC.h"                    // 自定义：选择城市的VC
#import "GPMapVC.h"                             // 自定义：显示地图的VC

@interface MainVC () <PFCitySelectorVCDelegate>

@property (nonatomic, strong) AMapLocationManager *locationManager; // 高德地图定位管理类

@property (nonatomic, strong) UIButton *currentCityBtn;             // 当前城市按钮
@property (nonatomic, strong) UIButton *openMapBtn;                 // 打开地图按钮

@property (nonatomic, strong) UIButton *networkStateBtn;            // 检测网络状态按钮
@property (nonatomic, strong) UIButton *networkAuthorizationBtn;    // 检测网络权限按钮
@property (nonatomic, strong) UIButton *testBtn;                    // 测试API按钮

@end

@implementation MainVC

#pragma mark - 控制器生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self setupUI];
    
    // 异步定位，更新当前城市按钮的title
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self updateCurrentCity];
    });
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.toolbarHidden = YES;
}


#pragma mark - 初始化UI


- (void)setupUI {
    
    [self myAddSubviews];
    
}


- (void)myAddSubviews {
    // YPF：地图功能按钮
    
    // 当前城市按钮
    _currentCityBtn = [UIButton pf_buttonWithTitle:@"中山市" andTitleColor:[UIColor orangeColor] andBorderWidth:1.0f andBorderColor:[[UIColor redColor] CGColor] ];
    [_currentCityBtn addTarget:self action:@selector(clickCurrentCityBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_currentCityBtn];
    [_currentCityBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(50);
        make.left.equalTo(self.view).offset(20);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(100);
    }];
    
    // 打开地图按钮
    _openMapBtn = [UIButton pf_buttonWithTitle:@"打开地图" andTitleColor:[UIColor orangeColor] andBorderWidth:1.0f andBorderColor:[[UIColor redColor] CGColor] ];
    [_openMapBtn addTarget:self action:@selector(clickOpenMapBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_openMapBtn];
    [_openMapBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view);
        make.right.equalTo(self.view).offset(-20);
        make.height.width.equalTo(self.currentCityBtn);
    }];
    
    
    // YPF：其他API测试按钮
    
    // 检测网络状态按钮
    _networkStateBtn = [UIButton pf_buttonWithTitle:@"检查网络" andTitleColor:[UIColor orangeColor] andBorderWidth:1.0f andBorderColor:[[UIColor redColor] CGColor] ];
    [_networkStateBtn addTarget:self action:@selector(clickNetworkStateBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_networkStateBtn];
    [_networkStateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(-20);
        make.left.height.width.equalTo(self.currentCityBtn);
    }];
    
    
    _networkAuthorizationBtn = [UIButton pf_buttonWithTitle:@"网络授权" andTitleColor:[UIColor orangeColor] andBorderWidth:1.0f andBorderColor:[[UIColor redColor] CGColor] ];
    [_networkAuthorizationBtn addTarget:self action:@selector(clickNetworkAuthorizationBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_networkAuthorizationBtn];
    [_networkAuthorizationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.networkStateBtn.mas_right).offset(20);
        make.height.width.bottom.equalTo(self.networkStateBtn);
    }];
    
    // 当前城市按钮
    _testBtn = [UIButton pf_buttonWithTitle:@"测试API" andTitleColor:[UIColor orangeColor] andBorderWidth:1.0f andBorderColor:[[UIColor redColor] CGColor] ];
    [self.testBtn addTarget:self action:@selector(clickTestBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.testBtn];
    [self.testBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.openMapBtn);
        make.height.width.bottom.equalTo(self.networkStateBtn);
    }];
}


#pragma mark - 按钮点击事件

- (void)clickCurrentCityBtn {
    PFCitySelectorVC *targetVC = [[PFCitySelectorVC alloc] init];
    targetVC.delegate = self;
    targetVC.title = @"城市";
    
//    // 给targetVC添加一个导航控制器
//    UINavigationController *naviC = [[UINavigationController alloc] initWithRootViewController:targetVC];
//    naviC.navigationBar.backItem.title = @"返回";
    
    [self presentViewController:targetVC animated:YES completion:nil];
}


- (void)clickOpenMapBtn {
    GPMapVC *targetVC = [[GPMapVC alloc] init];
    [self.navigationController pushViewController:targetVC animated:YES];
    
//    [self presentViewController:targetVC animated:YES completion:nil];
}


/**
 点击检查网络状态按钮
 */
- (void)clickNetworkStateBtn {
    [[GPAuthorizationManager sharedManager] gp_checkNetworkState];
}


/**
 点击检查网络权限按钮
 */
- (void)clickNetworkAuthorizationBtn {
    
    CTCellularData *cellularData = [[CTCellularData alloc] init];
    cellularData.cellularDataRestrictionDidUpdateNotifier =  ^(CTCellularDataRestrictedState state){
        //获取联网状态
        switch (state) {
            case kCTCellularDataRestricted: {
                NSLog(@"Restricrted");
                // ******************** Block by YPF. ********************
                // 添加提示弹框提示弹框
                
                // 显示弹框
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"网络受限！" message:@"是否开启网络权限？" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
                UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    // 跳转到对应本权限的设置页面
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }];
                [alertC addAction:leftAction];
                [alertC addAction:rightAction];
                [self presentViewController:alertC animated:YES completion:nil];
                // *******************************************************
            }
                break;
                
            case kCTCellularDataNotRestricted:
                NSLog(@"Not Restricted");
                break;
                
            case kCTCellularDataRestrictedStateUnknown:
                NSLog(@"Unknown");
                //                return @"Unknown"
                break;
            default:
                break;
        };
    };
}


/**
 点击测试API按钮
 */
- (void)clickTestBtn {
    NSString *urlString=@"openapp.jdmobile://virtual?params=%7B%22sourceValue%22:%220_productDetail_97%22,%22des%22:%22productDetail%22,%22skuId%22:%221140722%22,%22category%22:%22jump%22,%22sourceType%22:%22PCUBE_CHANNEL%22%7D";
    NSURL *url=[NSURL URLWithString:urlString];
    [[UIApplication sharedApplication] openURL:url];
}


#pragma mark - 可移植代码-更新当前城市名

/**
 更新城市名（异步单次定位，获取逆地理城市名后判断弹窗）
 */
- (void)updateCurrentCity {
    
    if (![self checkLocationAuthorization]) {
        // ******************** Block by YPF. ********************
        // 添加提示弹框提示弹框
        
        // 显示弹框
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"定位权限受限！" message:@"是否开启定位权限？" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            return;
        }];
        UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 跳转到对应本权限的设置页面
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alertC addAction:leftAction];
        [alertC addAction:rightAction];
        [self presentViewController:alertC animated:YES completion:nil];
        // *******************************************************
    }
    
    _locationManager = [[AMapLocationManager alloc] init];
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    _locationManager.locationTimeout = 2;
    _locationManager.reGeocodeTimeout = 2;
    
    GPWeakSelf;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (!error && regeocode) {
            NSLog(@"reGeocode:%@", regeocode);
            if (regeocode.city != weakSelf.currentCityBtn.currentTitle) {
                
                // 显示弹框
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"检测到当前处于%@", regeocode.city] message:@"是否切换？" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    return;
                }];
                UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.currentCityBtn setTitle:regeocode.city forState:UIControlStateNormal];    // 更新城市名
                        [weakSelf pf_selectCityWithName:regeocode.city];       // 做一些切换城市的事情
                    });
                }];
                [alertC addAction:leftAction];
                [alertC addAction:rightAction];
                [self presentViewController:alertC animated:YES completion:nil];
                // *******************************************************
            }
        }
    }];
    
}


// 检查定位权限
- (BOOL)checkLocationAuthorization {
    
    if (CLLocationManager.locationServicesEnabled) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||
            [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways ||
            [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
            return YES;
        } else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
            return NO;
        }
    }
    return NO;
}


/**
 做一些切换城市的事情
 
 @param cityName 新城市名
 */
- (void)pf_selectCityWithName:(NSString *)cityName {
    
}

#pragma mark - PFCitySelectorVCDelegate

- (void)cityName:(NSString *)name {
    [self.currentCityBtn setTitle:name forState:UIControlStateNormal];
    [self pf_selectCityWithName:name];
}

@end
